package org.odata4j.test.integration.producer.jpa.northwind;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.odata4j.test.integration.RuntimeFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NorthwindTestUtils2 extends NorthwindTestUtils {

  private static final Logger LOGGER = LoggerFactory.getLogger(NorthwindTestUtils2.class);
  
  /**
   * Construct an instance with the given {@link RuntimeFacade}.
   * 
   * @param rtFacade
   */
  public NorthwindTestUtils2(RuntimeFacade rtFacade) {
    super(rtFacade);
  }
  
  protected void assertJsonResultMatchesExpected(String result, String expect) {
    Map<String,Object> valuesMapExpect = getValuesMapFromJSON(expect);
    Map<String,Object> valuesMapResult = getValuesMapFromJSON(result);
    
    if (valuesMapExpect.equals(valuesMapResult)) {
      LOGGER.debug("the expected string matches the result");
    }
    else {
      LOGGER.error("valuesMapExpect=" + valuesMapExpect);
      LOGGER.error("valuesMapResult=" + valuesMapResult);
      Assert.fail("the result JSON string does not match the expected value");
    }
  }
  
  private Map<String,Object> getValuesMapFromJSON(String str) {
    ObjectMapper mapper = new ObjectMapper();
    try {
      String charset = "UTF-8";
      InputStream is = new ByteArrayInputStream(str.getBytes(charset));
      
      @SuppressWarnings("unchecked")
      Map<String,Object> valuesMap = mapper.readValue(is, Map.class);
      return valuesMap;
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }

}
